<?php
// +----------------------------------------------------------------------
// | Copyright (c) 2020 All rights reserved.
// +----------------------------------------------------------------------
// | User: Simony <1362229026@qq.com>
// | wechat: Shen86579595
// +----------------------------------------------------------------------

namespace app\common\logic\content;

use easemob\EasemobIm;
use \think\Db;
use OSS\OssClient;
use OSS\Core\OssException;

class ContentLogic
{

    /**
     * User: Simony
     * Function: 发布内容
     * @param $member_id
     * @param $data
     * @param $same_sex_status
     * @param int $type 1动态 2项目
     */
    public function publishContent($member_id, $data, $same_sex_status, $type = 1)
    {
        $authLogic = model('common/AuthLogic', 'logic');
        $use_auth_res = $authLogic->isUseAuth($member_id, true); //校验使用权限
        if (isset($use_auth_res['code']) && $use_auth_res['code'] != SUCCESS) return ds_arr($use_auth_res['code'], $use_auth_res['msg'], $use_auth_res['result']);

        if (in_array($type, [1, 2])) ds_arr(ERROR, '发布的内容必须时动态或者项目');
        //校验
        $valdate = validate('mobileapp/Content');
        $valdara_scene = $type == 1 ? 'publishDynamic' : 'publishProgram';
        if (!$valdate->check($data, [], $valdara_scene)) return ds_arr(ERROR, $valdate->getError());

        //model
        $memberModel = model('common/member/Member');
        $member = $memberModel->getInfoByID($member_id);
        //judge
        if (empty($member)) ds_arr(ERROR, '会员不存在');

        if ($same_sex_status == 1) {  //代表对同性不隐藏 为了优化查询
            $data['same_sex_status'] = 3; //对所有人显示
        } else { //同性隐藏
            $data['same_sex_status'] = $member['sex'] == 1 ? 2 : 1;  //对谁显示 男的时候显示女，女的时候显示男
        }


        $authLogic = model('common/AuthLogic', 'logic');
        $day_release_num = $res = $authLogic->getDayReleaseContentNum($member_id, $type);

        if (isset($res['code']) && $res['code'] != SUCCESS) return ds_arr($res['code'], $res['msg'], $res['result']);


        $current_time = time();
        if ($day_release_num != -1) {
            $contentModel = model('common/content/Content');
            $issuedTodayNum = $contentModel->issuedTodayNum($member_id, $type);

            if ($day_release_num <= $issuedTodayNum) {

                $content_type = model('common/content/ContentType')->getInfoByID($type);
                $price = $content_type['price'] > 0 ? $content_type['price'] : 0;
                if (floatval($member['available_balance']) < floatval($price)) return ds_arr(JUMP_RECHARGE, '余额不足，还差' . ($price - $member['available_balance']) . '个金币,请及时充值', ['balance' => $member['available_balance']]);

                $add_release_content_pay_log_data = [
                    'member_id' => $member_id,
                    'type' => $type,
                    'create_time' => $current_time,
                    'price' => $price,
                    'pay_type' => 0,
                    'state' => 1,
                    'pay_time' => $current_time
                ];

                //添加发布收费内容日志
                $add_release_content_pay_log_res = model('common/release/ReleaseContentPayLog')->add($add_release_content_pay_log_data);
                if (!$add_release_content_pay_log_res) return ds_arr(ERROR, '收费日志添加失败');

                //余额变更记录
                $desc = '付费发布' . $content_type['name'];
                $update_available_balance_res = model('common/member/MemberLogic', 'logic')->updateAvailableBalance($member_id, -$price, 0, 0, $desc);
                if ($update_available_balance_res['code'] != SUCCESS) return ds_arr($update_available_balance_res['code'], $update_available_balance_res['msg']);

            }
        }

        //添加内容
        $res = model('common/content/Content')->add($data);
        if (!$res) ds_arr(ERROR, '发布失败');


        //推送消息  0聊天消息,1评价通知 2节目通知 3报名通知 4申请通知 5评论通知 6收益提醒通知 7消息通知
        $follow_member_ids = model('common/member/FollowBlacklist')->getCol('member_id', ['been_member_id' => $member_id, 'type' => 1, 'status' => 1]);
        if ($type == 2 && !empty($follow_member_ids)) model('common/Noticle', 'logic')->sendTxtSysNotice($follow_member_ids, $member['nickname'] . '发布了一条节目，点击查看', 2);

        return ds_arr(SUCCESS, '发布成功', ['id' => $res]);
    }

    /**
     * User:Simony
     * Function: 内容点赞
     * @param $id
     */
    public function like($content_id, $member_id)
    {
        $memberModel = model('common/member/Member');
        $contentModel = model('common/content/Content');
        $content = $contentModel->getInfoByID($content_id, 'like');
        $member = $memberModel->getInfoByID($member_id);

        if (empty($content)) return ds_arr(ERROR, '内容不存在');
        $like = json_decode($content['like'], true); //获取所有的点赞
        $like = is_array($like) ? $like : [];

        if (in_array($member_id, $like)) {
            $like = array_diff($like, [$member_id]);
            $op_res = $contentModel->setValDecID($content_id, 'like_num');
        } else {
            $like[] = $member_id;
            $op_res = $contentModel->setValIncByID($content_id, 'like_num');
        }


        if (!$op_res) return ds_arr(ERROR, '操作失败');


        $res = $contentModel->editById($content_id, ['like' => json_encode($like)]);
        if (!$res) return ds_arr(ERROR, '操作失败');

        return ds_arr(SUCCESS, '操作成功', ['member_id' => $member_id, 'avatar' => $member['avatar'], 'sex' => $member['sex']]);
    }


    /**
     * User:Simony
     * Function:举报内容
     * @param $member_id
     * @param $content_id
     * @param $desc
     * @param $type_id
     * @return array
     */
    public function reportContent($member_id, $content_id, $type_id, $desc)
    {

        $content = model('common/content/Content')->getInfoByID($content_id, 'member_id');
        if (empty($content)) return ds_arr(ERROR, '举报内容不存在');
        if ($member_id == $content['member_id']) return ds_arr(ERROR, '自己不能举报自己');

        $report_type = model('common/report/ReportType')->getInfoById($type_id);
        if (empty($report_type)) return ds_arr(ERROR, '举报类型不存在');

        $data = [
            'member_id' => $member_id,
            'content_id' => $content_id,
            'report_member_id' => $content['member_id'],
            'type_id' => $type_id,
            'desc' => $desc,
            'state' => 0,
            'category' => 1,
            'create_time' => time()
        ];

        $reportModel = model('common/report/ReportUser');
        $content = $reportModel->getInfo(['member_id' => $member_id, 'content_id' => $content_id, 'category' => 1]);
        if ($content) return ds_arr(ERROR, '请勿重复举报');

        $res = $reportModel->add($data);
        return $res ? ds_arr(SUCCESS, '举报成功', ['id' => $res]) : ds_arr(ERROR, '举报失败');
    }


    /**
     * User:Simony
     * Function: 回复内容
     * @param $memberId
     * @param $content_id
     * @param $data
     * @return array
     */
    public function replyContent($memberId, $content_id, $data, $url_list)
    {
        $memberModel = model('common/member/Member');
        $member = $memberModel->getInfoByID($memberId);
        if (empty($member)) ds_arr(ERROR, '会员不存在');

        $data = [
            'content_id' => $content_id,
            'pid' => $data['pid'],
            'content' => $data['content'],
            'member_id' => $memberId,
            'type' => $data['type'],
            'create_time' => time(),
        ];


        //judge
        $valdate = validate('mobileapp/Comment');

        $scene = $data['type'] == 1 ? 'comment' : 'signUp';
        $msg_name = $data['type'] == 1 ? '评论' : '报名';
        if (!$valdate->check($data, [], $scene)) return ds_arr(ERROR, $valdate->getError());


        //
        $contentModel = model('common/content/Content');
        $content = $contentModel->getInfoByID($content_id, 'member_id,comment_status,type');
        if (empty($content)) return ds_arr(ERROR, '内容不存在');
        if ($data['type'] == 1 && $content['comment_status'] == 0) return ds_arr(ERROR, '评论未开启');

        if ($content['type'] == 1) {//动态
            if ($data['type'] == 2) return ds_arr(ERROR, '动态不允许报名');
        }

        //
        $commentModel = model('common/content/Comment');
        if ($data['pid'] > 0) { //回复
            $pid_comment = $commentModel->getInfoByID($data['pid']);
            if (empty($pid_comment)) return ds_arr(ERROR, '回复的内容不存在');
            if ($pid_comment['member_id'] == $memberId) return ds_arr(ERROR, '不能自己回复自己的评论');
            if ($memberId != $content['member_id']) { //当前登录用户不是发帖用户
                if ($pid_comment['member_id'] != $content['member_id']) return ds_arr(ERROR, '不能回复非发帖人的评论');
            }
        } else { //评论
            if ($memberId == $content['member_id']) return ds_arr(ERROR, '自己不能评论自己发布的内容'); ////当前登录用户不是发帖用户
        }


        $res = $commentModel->add($data);
        if (!$res) return ds_arr(ERROR, $msg_name . '失败');

        $set_field = 'comment_num';//评论数
        if ($data['type'] == 2) { //报名添加图片
            $sign_res = $this->signUp($memberId, $content_id, $res, $url_list);
            if ($sign_res['code'] != SUCCESS) return ds_arr($sign_res['code'], $sign_res['msg']);
            $set_field = 'sign_up_num'; //报名数
        } else {
            //推送消息  0聊天消息,1评价通知 2节目通知 3报名通知 4申请通知 5评论通知 6收益提醒通知 7消息通知
            if ($data['pid'] == 0) {
                model('common/Noticle', 'logic')->sendTxtSysNotice($content['member_id'], $member['nickname'] . '评论了您得' . (($content['type'] == 1 ? '动态' : '节目')) . '，快点看看吧', 5);
            }
        }


        $op_res = $contentModel->setValIncByID($content_id, $set_field);
        if (!$op_res) return ds_arr(ERROR, $msg_name . '失败');

        return ds_arr(SUCCESS, $msg_name . '成功', ['id' => $res]);
    }


    /**
     * User:Simony
     * Function:
     * @param $member_id
     * @param  type  类型 1关注 2最新 3节目 4动态
     * @param  category_id  分类id  节目时提交id
     * @param $location 地区
     * @param $appoint_member_id 指定显示用户
     * @return array
     */
    public function getContentList($member_id, $page = 10, $type, $category_id, $location, $appoint_member_id = -1)
    {
        //model
        $memberModel = model('common/member/Member');
        $member = $memberModel->getInfoByID($member_id);
        //judge
        if (empty($member)) ds_arr(ERROR, '会员不存在');
        $contentModel = model('common/content/Content');

        //where
        $where = [];
        $whereOr = [['c.same_sex_status', 'in', "{$member['sex']}, 3"]];
        $order = 'c.create_time desc';
        $field = "c.date_type,c_c.id as category_id,c_c.name as category_name,m.sex,m.avatar,m.nickname,m.video_verify,m.real_verify,m.level,c.content,c.id,c.location,c.expect_object,c.member_id,c.begin_date,c.end_date,c.create_time,c.type,c.like,c.like_num,c.comment_num,c.sign_up_num,c.comment_status";
        //set params
        switch ($type) { //1关注
            case 1:  //关注
                if ($appoint_member_id > 0) $where['c.member_id'] = $appoint_member_id;
                $been_member_ids = model('common/member/FollowBlacklist')->getCol('been_member_id', ['member_id' => $member_id]);
                $where['c.member_id'] = empty($been_member_ids) ? 0 : $been_member_ids;  //关注用户
                break;
            case 2:  //最新
                if ($appoint_member_id > 0) $where['c.member_id'] = $appoint_member_id;
                $whereOr[] = ['c.member_id', 'eq', $member_id];
                break;
            case 3:   //节目
                $where['c.type'] = 2;

                if ($appoint_member_id > 0) $where['c.member_id'] = $appoint_member_id;
                if ($category_id > 0) $where['c.category_id'] = $category_id;
                if ($location) $where['c.location'] = $location;
                $whereOr[] = ['c.member_id', 'eq', $member_id];
                break;
            case 4:   //动态
                $where['c.type'] = 1;
                if ($appoint_member_id > 0) $where['c.member_id'] = $appoint_member_id;
//                if ($category_id > 0) $where['c.category_id'] = $category_id;
                if ($location) $where['c.location'] = $location;
                $whereOr[] = ['c.member_id', 'eq', $member_id];
                break;
            default:
                return ds_arr(ERROR, '类型错误');
        }

        $field .= ',f2.id as is_sign_up';
        $list = $contentModel->getPageContentList($where, $page, $field, $order, $whereOr, $member_id);
        if (isset($list['data'])) {
            foreach ($list['data'] as &$v) {
                $like = empty($v['like']) ? [] : json_decode($v['like'], true);
                $like = is_array($like) ? $like : [];
                unset($v['like']);
                $v['is_like'] = in_array($member_id, $like) ? 1 : 0;
                $v['url'] = [];
                if (isset($v['file'])) {
                    foreach ($v['file'] as $key => $value) {
                        $v['url'][] = $value['url'];
                    }
                }
                $v['is_sign_up'] = !is_null($v['is_sign_up']) ? 1 : 0;
                unset($v['file']);
            }
        }

        return ds_arr(SUCCESS, '获取成功', $list);

    }

    /**
     * User:Simony
     * Function:获取内容详细
     */
    public function getContentDetail($memberId, $content_id)
    {
        //model
        $contentModel = model('common/content/Content');

        $where = [];
        $where['c.id'] = $content_id;
        $field = 'm.level,m.sex,m.avatar,m.nickname,m.video_verify,m.real_verify,c_c.id as category_id,c_c.name as category_name,c.content,c.id,c.location,c.expect_object,c.member_id,c.begin_date,c.end_date,c.create_time,c.type,c.date_type,c.like,c.like_num,c.comment_num,c.sign_up_num';
        $content = $contentModel->alias('c')
            ->field($field)
            ->join('member m', 'm.id=c.member_id')
            ->join('content_category c_c', 'c_c.id=c.category_id', 'left')
            ->with(['file' => function ($q) {
                $q->field('table_id,url,id,type')->where(['type' => 5]);  //文件条件
            }])
            ->where($where)->find();
        if (empty($content)) return ds_arr(ERROR, '内容不存在');

        $content = $content->toArray();

        $commentModel = model('common/content/Comment');
        $fileModel = model('common/member/File');

        $self_view = $content['member_id'] == $memberId ? 1 : 0; //自己看自己的
        //评论+报名列表
        $comment_field = 'c_c.content,c_c.id,c_c.member_id,c_c.pid,c_c.create_time,m.nickname,m.avatar,m.sex,m.real_verify,m.video_verify';
        $sign_field = 'f.url,f.create_time,m.id as member_id,m.nickname,m.sex,m.avatar,m.sex,m.real_verify,m.video_verify';
        if ($self_view == 1) {  //看所有人评论
            $comment_list = $commentModel->getTree(0, ['c_c.content_id' => $content_id, 'c_c.type' => 1], $comment_field);
            $sign_where = ['f.table_id' => $content_id, 'f.type' => 6,'f.status'=>1];
            $sign_up_list = $fileModel->getFileList($sign_where, $sign_field, 'f.id asc', 0);
        } else { //只能看着自己与发帖人的评论
            $comment_where = [
                ['c_c.content_id', 'eq', $content_id],
                ['c_c.member_id', 'in', $memberId . ',' . $content['member_id']],
                ['c_c.type', 'eq', 1],
            ];
            $comment_list = $commentModel->getTree(0, $comment_where, $comment_field);
            $sign_where = ['f.member_id' => $memberId, 'f.table_id' => $content_id, 'f.type' => 6,'f.status'=>1];
            $sign_up_list = $fileModel->getFileList($sign_where, $sign_field, 'f.id asc', 0);
        }

        //处理数据
        $data = [];
        $data['self_view'] = $self_view;
        if (isset($content['file'])) {
            $content['url'] = [];
            foreach ($content['file'] as $value) $content['url'][] = $value['url'];
            unset($content['file']);
        }
        $like = empty($content['like']) ? [] : json_decode($content['like'], true);
        $like = is_array($like) ? $like : [];
        $last_member_id = array_slice($like, -8);
        $data['like_list'] = model('common/member/Member')->getList(['id' => $last_member_id], 7, 'id,avatar,sex');
        $data['is_like'] = in_array($memberId, $like) ? 1 : 0;
        unset($content['like']);

        $data['self_view'] = $self_view;
        $data['is_sign_up'] = $fileModel->isExist(['table_id' => $content_id, 'type' => 6, 'member_id' => $memberId]) ? 1 : 0;
        $data['sign_up_list'] = $sign_up_list;
        $data['comment_list'] = $comment_list;
        $data = array_merge($content, $data);
        return ds_arr(SUCCESS, '获取成功', $data);
    }


    /**
     * User:Simony
     * Function: 项目报名
     */
    public function signUp($member_id, $content_id, $comment_id, $url_list)
    {

        $url_arr = $url_list ? explode(',', $url_list) : [];
        if (empty($url_arr)) return ds_arr(ERROR, '报名头像不能为空');


        $type = 6;//文件类型 6：评论&报名照片  不要后面的 (1：照片、2：阅后即焚、3：红包照片、4：审核照片视频、5：内容照片)

        $memberModel = model('common/member/Member');
        $member = $memberModel->getInfoByID($member_id);
        if (empty($member)) ds_arr(ERROR, '会员不存在');

        $contentModel = model('common/content/Content');
        $content = $contentModel->getInfoByID($content_id);
        if (empty($content)) return ds_arr(ERROR, '内容不存在');
        if (time() > $content['end_date']) return ds_arr(ERROR, '活动已截止');

        $fileModel = model('common/member/File');
        if ($fileModel->isExist(['member_id' => $member_id, 'table_id' => $content_id, 'type' => $type])) return ds_arr(ERROR, '请勿重复报名');

//        $fileLogic = model('common/file/FileLogic', 'logic');
//        $upload_res = $fileLogic->base64Image(config('app.image_path.sign_up'));
//        if ($upload_res['code'] != SUCCESS) return ds_arr($upload_res['code'], $upload_res['msg']);

        $add_data_all = [];
        $fileLogic = model('common/file/FileLogic','logic');
        foreach ($url_arr as $v) {
            if (!$fileLogic->fileExists ($v)) return ds_arr(ERROR, '图片不存在请重新上传');
            $add_data_all[] = [
                'member_id' => $member_id,
                'table_id' => $content_id,
                'type' => $type,
                'status' => 1,
                'url' => $v,
                'create_time' => time()
            ];
        }
        $res = $fileModel->insertAll($add_data_all);
        if (!$res) return ds_arr(ERROR, '操作失败2');

        //推送消息  0聊天消息,1评价通知 2节目通知 3报名通知 4申请通知 5评论通知 6收益提醒通知 7消息通知
        model('common/Noticle', 'logic')->sendTxtSysNotice($content['member_id'], $member['nickname'] . '报名了您得节目，快去看看吧', 3);

        return ds_arr(SUCCESS, '操作成功');
    }


    /**
     * User:Simony
     * Function: 获取自己的内容
     * @param $member_id
     * @param $type 1是动态 2节目
     */
    public function myContent($member_id, $page, $type)
    {
        $contentModel = model('common/content/Content');

        $where = [
            'c.member_id' => $member_id, //自己发布的
            'c.type' => $type, //类型
        ];
        $order = 'c.id desc';
        $field = "c.date_type,c_c.id as category_id,c_c.name as category_name,m.sex,m.avatar,m.nickname,m.video_verify,m.real_verify,m.level,c.content,c.id,c.location,c.expect_object,c.member_id,c.begin_date,c.end_date,c.create_time,c.type,c.like,c.like_num,c.comment_num,c.sign_up_num,c.comment_status";

        $list = $contentModel->getPageContentList($where, $page, $field, $order);
        if (isset($list['data'])) {
            foreach ($list['data'] as &$v) {
                $like = empty($v['like']) ? [] : json_decode($v['like'], true);
                $like = is_array($like) ? $like : [];
                unset($v['like']);
                $v['is_like'] = in_array($member_id, $like) ? 1 : 0;
                $v['url'] = [];
                if (isset($v['file'])) {
                    foreach ($v['file'] as $key => $value) {
                        $v['url'][] = $value['url'];
                    }
                }
                unset($v['file']);
            }
        }

        return ds_arr(SUCCESS, '获取成功', $list);
    }


    /**
     * User: Simony
     * Function:删除评论
     * @param $member_id
     * @param $comment_id
     */
    public function delComment($member_id, $comment_id)
    {
        $memberModel = model('common/member/Member');
        $commentModel = model('common/content/Comment');
        $contentModel = model('common/content/Content');

        $member = $memberModel->getInfoByID($member_id);
        if (empty($member)) return ds_arr(ERROR, '当前登录用户不存在');

        $comment = $commentModel->getInfoByID($comment_id);
        if (empty($comment)) return ds_arr(ERROR, '评论不存在');
        if ($comment['member_id'] != $member_id) return ds_arr(ERROR, '不能删除别人的评论');
        if ($comment['pid'] != 0) return ds_arr(ERROR, '回复不能删除'); //pid=0 才是评论，其余都是回复

        $ids_arr = $commentModel->getChildren($comment_id);
        $ids_arr[] = $comment_id;

        $where['id'] = $ids_arr;
        $res = $commentModel->del($where);
        if (!$res) ds_arr(ERROR, '操作失败');

        $res = $contentModel->setValDecID($comment['content_id'], 'comment_num', count($ids_arr));
        return $res ? ds_arr(SUCCESS, '操作成功') : ds_arr(ERROR, '操作失败');
    }

}
